package com.ejuornal.service.impl;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Component;

import com.ejuornal.bean.Page;
import com.ejuornal.bean.Permission;
import com.ejuornal.bean.PermissionGroup;
import com.ejuornal.bean.RolePermission;
import com.ejuornal.bean.vo.PermissionVO;
import com.ejuornal.dao.PermissionDao;
import com.ejuornal.dao.PermissionGroupDAO;
import com.ejuornal.service.PermissionService;
@Component("permissionService")
public class PermissionServiceImpl implements PermissionService{
    private PermissionDao permissionDao;
    private PermissionGroupDAO pgDao;

    @Override
	public List<PermissionVO> findPermissionVO(int roleId) {
		List<PermissionGroup> groupNames = pgDao.findNamesByRoleId(roleId);
		List<PermissionVO> pv = new ArrayList<PermissionVO>();
		for(int i=0; i < groupNames.size(); i++) {
		    PermissionVO p = new PermissionVO();
			PermissionGroup pg  = groupNames.get(i);
			String pgname = pg.getPgName();
			int pgid = pg.getPgId();
			List<Permission> permissions = permissionDao.findByPgId(pgid, roleId);
			
			if(permissions != null) {
			    p.setPermission(permissions);
			}
			p.setGroupName(pgname);
			pv.add(p);
		}
		return pv;
	}
    
	public void add(Permission permission) {
        String sql = "insert into t_permission(pname, pdesc, pgId) value(?,?,?)";
        permissionDao.add(sql, permission.getPname(), permission.getPdesc(), permission.getPgId());
    }
    
    public Page<Permission> find(int current_record, String url, int pgId) {
        String sql = "where pgId=?";
        Page<Permission> page = permissionDao.find(current_record, url, sql, new Object[]{pgId});
        return page;
    }
    
    public PermissionDao getPermissionDao() {
        return permissionDao;
    }
    @Resource(name="permissionDao")
    public void setPermissionDao(PermissionDao permissionDao) {
        this.permissionDao = permissionDao;
    }

    public boolean delete(int pid) {
        return permissionDao.delete(pid);
    }

	@Override
	public List<Permission> findByRoleId(int roleId) {
		return permissionDao.findByRoleId(roleId);
	}

	@Override
	public List<Permission> findByNotIntRole(int roleId) {
		return permissionDao.findByNotIntRole(roleId);
	}

	@Override
	public boolean addRolePermission(RolePermission rp) {
		return permissionDao.addRolePermission(rp);
	}

	 public PermissionGroupDAO getPgDao() {
			return pgDao;
	}
	 @Resource(name="permissionGroupDao")
	public void setPgDao(PermissionGroupDAO pgDao) {
		this.pgDao = pgDao;
	}
}
